package showyourself;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Date;


/**
 * Servlet implementation class registration
 */
@WebServlet("/registration")
public class registration extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public registration() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String connectionURL = "jdbc:mysql://127.0.0.1/global";
		Connection connection=null;
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		
		//String uId = req.getParameter("userId");
		String firstname = req.getParameter("firstname");
		String lastname = req.getParameter("lastname");
		String email = req.getParameter("email");
		String dateOfBirth = req.getParameter("dateOfBirth");
		String password = req.getParameter("password"); 
		Date now = new Date();
		Timestamp lastLoggIn = new Timestamp(now.getTime());
		
		try {
			Class.forName("org.gjt.mm.mysql.Driver");
			connection = DriverManager.getConnection(connectionURL, "root", "esfna7640");
			String sql = "insert into users(Firstname, Lastname, Email, DateOfBirth, Password, LastLoggIn) values (?,?,?,?,?,?)";
			PreparedStatement pst = connection.prepareStatement(sql);
			pst.setString(1, firstname);
			pst.setString(2, lastname);
			pst.setString(3, email);
			pst.setString(4, dateOfBirth);
			pst.setString(5, password);
			pst.setTimestamp(6, lastLoggIn);
			pst.executeUpdate();
			pst.close();
			
			HttpSession session = req.getSession();
			session.setAttribute("email", email);
		}
		catch(ClassNotFoundException e){
			out.println("Couldn't load database driver: " + e.getMessage());
		}
		catch(SQLException e){
			out.println("SQLException caught: " + e.getMessage());
		}
		catch (Exception e){
			out.println(e);
		}
		finally {

			try {
				if (connection != null) 
					connection.close();
			}
			catch (SQLException ignored){
				out.println(ignored);
			}
		}
		
		res.sendRedirect("index.jsp");
	}

}
